package com.fanshuai.springcloud.config;

import com.fanshuai.springcloud.component.HtmlJsonMessageConverter;
import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.codec.Decoder;
import feign.codec.Encoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.HttpMessageConverter;

import java.util.ArrayList;
import java.util.List;

public class BookServiceConfig {
    @Autowired
    private ObjectFactory<HttpMessageConverters> messageConverters;

    @Bean
    public Encoder encoder() {
        return new SpringEncoder(messageConverters);
    }

    @Bean
    public Decoder decoder() {
        List<HttpMessageConverter<?>> converters = new ArrayList<>(messageConverters.getObject().getConverters());
        converters.add(new HtmlJsonMessageConverter());

        return new ResponseEntityDecoder(new SpringDecoder(() -> {
            return new HttpMessageConverters(converters);
        }));
    }

    @Bean
    public Logger.Level loggerLevel() {
        return Logger.Level.FULL;
    }

    @Bean
    public RequestInterceptor requestInterceptor() {
        return (RequestTemplate template) -> {
            template.header("service", "book-nacos");
        };
    }
}
